﻿using Abp.Reflection.Extensions;
using Abp.UI;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using SportsPlatform.Base;
using SportsPlatform.Configuration;
using SportsPlatform.Consts;
using SportsPlatform.Dto.Other;
using SportsPlatform.Enums;
using SportsPlatform.Query.File;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SportsPlatform.Controllers
{
    /// <summary>
    /// 文件上传
    /// </summary>

    [Route("api/[controller]/[action]")]
    [AllowAnonymousAttribute]
    public class UploadFileController : SportsPlatformControllerBase
    {
        private readonly IConfiguration _appConfiguration;
        private readonly IWebHostEnvironment _webHostEnvironment;

        /// <summary>
        /// 构造函数
        /// </summary>
        public UploadFileController(IWebHostEnvironment env)
        {
            _webHostEnvironment = env;
            _appConfiguration = AppConfigurations.Get(typeof(UploadFileController).GetAssembly().GetDirectoryPathOrNull());
        }

        /// <summary>
        /// 上传字节文件        
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// 
        [HttpPost]
        public async Task<ResultDto<UploadFileDto>> UploadFileBase64Str([FromBody] UploadFilesBase64StrQuery query)
        {
            return await Task.Run(() =>
            {
                var result = new ResultDto<UploadFileDto>();
                var dto = new UploadFileDto();
                var uploadsFolderPath = _webHostEnvironment.WebRootPath;    //文件保存的路径地址
                var relativePath = "";  //相对路径
                var dateNow = DateTime.Now.ToString("yyyy-MM-dd");    //当前日期                
                switch (query.UploadFileType)
                {
                    case UploadFileTypeEnum.File:
                        uploadsFolderPath += _appConfiguration["Setting:UploadFileRoot:File"] + dateNow + "/";
                        relativePath = _appConfiguration["Setting:UploadFileRoot:File"] + dateNow + "/";
                        break;
                    case UploadFileTypeEnum.Img:
                        uploadsFolderPath += _appConfiguration["Setting:UploadFileRoot:Img"] + dateNow + "/";
                        relativePath = _appConfiguration["Setting:UploadFileRoot:Img"] + dateNow + "/";
                        break;
                    default:
                        result.Code = HttpResultCode.Error;
                        result.Message = "上传的文件类型错误！";
                        result.IsSuccess = false;
                        return result;
                }
                var imgData = query.Base64Str.Split(',')[1];
                var bt = Convert.FromBase64String(imgData); //获取文件base64
                try
                {
                    if (!Directory.Exists(uploadsFolderPath))
                    {
                        Directory.CreateDirectory(uploadsFolderPath);
                    }
                    var fileName = Guid.NewGuid().ToString();
                    if (query.UploadFileType == UploadFileTypeEnum.Img)
                    {
                        fileName += ".png";
                    }
                    var savePath = uploadsFolderPath + fileName;
                    FileStream fs = new FileStream(savePath, FileMode.CreateNew);
                    fs.Write(bt, 0, bt.Length);
                    fs.Close();
                    //result.UserId = AbpSession.UserId.Value;
                    dto.Url = Path.Combine(relativePath, fileName);
                    dto.FilePath = savePath;
                    result.IsSuccess = true;
                    result.Message = "上传成功";
                    result.Code = HttpResultCode.Success;
                    result.Data = dto;
                    return result;
                }
                catch (Exception ex)
                {
                    throw new UserFriendlyException(ex.Message);
                }
            });
        }
    }
}
